// 引入依赖的模块，ClientIdCredential 用于创建客户端凭证实例
const { ClientIdCredential } = require('@agconnect/common-server/dist/credential-service/clientid-credential');

// 导出 getCredential 函数，它接收 context 和 logger 作为参数
export const getCredential = (context, logger) => {
  try {
    // 尝试解析环境变量 PROJECT_CREDENTIAL 中的 JSON 字符串
    const credential = JSON.parse(context.env.PROJECT_CREDENTIAL);
    // 根据凭证类型创建不同参数的 ClientIdCredential 实例
    if (credential.type === 'team_client_id') {
      // 如果凭证类型为 team_client_id
      return new ClientIdCredential('', '', credential.developer_id, credential.type, credential.client_id,
        credential.client_secret, credential.configuration_version);
    } else if (credential.type === 'project_client_id') {
      // 如果凭证类型为 project_client_id
      return new ClientIdCredential(credential.project_id, credential.region, credential.developer_id, credential.type,
        credential.client_id, credential.client_secret, credential.configuration_version);
    }
  } catch {
    // 如果解析过程中发生错误，记录错误信息
    logger.error('get project credential failed');
  }
};